<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 卡片头 -->
        <div slot="header" class="clearfix">
          <span>{{ `试题${$route.query.id ? '修改' : '录入'}` }}</span>
        </div>
        <!-- 表单 -->
        <el-form
          :model="form"
          ref="form"
          :rules="rules"
          label-width="100px"
          style="margin-left: 20px"
        >
          <!-- 学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              style="width: 35%"
              v-model="form.subjectID"
              placeholder="请选择"
              @change="changeSubjectTo"
            >
              <el-option
                v-for="item in subjectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              style="width: 35%"
              v-model="form.catalogID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in directorysList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              style="width: 35%"
              v-model="form.enterpriseID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in enterpriseList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市：" prop="province">
            <!-- 省份 -->
            <el-col :span="4" style="margin-right: 20px">
              <el-select
                v-model="form.province"
                placeholder="请选择"
                @change="changeProvince"
              >
                <el-option
                  v-for="item in provincesList"
                  :key="item.id"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-col>
            <!-- 区域 -->
            <el-col :span="4">
              <el-select v-model="form.city" placeholder="请选择">
                <el-option
                  v-for="item in citysList"
                  :key="item.id"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select
              style="width: 35%"
              v-model="form.direction"
              placeholder="请选择"
            >
              <el-option
                v-for="item in directionList"
                :key="item.id"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="form.questionType">
              <el-radio
                v-for="item in questionTypeList"
                :key="item.id"
                :label="item.value"
                @change="changeQuestionType"
              >
                <template>
                  {{ item.label }}
                </template>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio
                v-for="item in difficultyList"
                :key="item.id"
                :label="item.value"
              >
                <template>
                  {{ item.label }}
                </template>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干：" prop="question">
            <quill-editor
              v-model.trim="form.question"
              :options="editorOption"
            />
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项：" v-show="form.questionType !== 3">
            <div
              v-for="(item, index) in form.options"
              :key="item.id"
              style="display: flex; align-items: center; margin-bottom: 20px"
            >
              <!-- 单选 -->
              <el-radio-group
                v-model="item.isRight"
                v-show="form.questionType === 1"
                @change="changeRadio(item.code)"
              >
                <el-radio :label="true">
                  <template>{{ item.code }}：</template>
                </el-radio>
              </el-radio-group>
              <!-- 多选 -->
              <el-checkbox
                v-show="form.questionType === 2"
                v-model="item.isRight"
              >
                <template>{{ item.code }}：</template>
              </el-checkbox>

              <!-- 输入框 -->
              <el-input style="width: 240px" v-model="item.title"></el-input>
              <!-- 上传图片 -->
              <input
                type="file"
                ref="inp"
                @change="chooseImg($event, index)"
                hidden
              />
              <div class="upload" @click="clickFile(index)">
                <img :src="item.img" alt="" class="img" />
                <span>上传图片</span>
                <i
                  class="el-icon-circle-close close"
                  @click.stop="delImg(index)"
                ></i>
              </div>
            </div>
            <el-button
              type="danger"
              size="small"
              @click="addOptions"
              :disabled="form.questionType !== 2"
            >
              +增加选项与答案
            </el-button>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频：">
            <el-input v-model="form.videoURL" style="width: 35%"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析：" prop="answer">
            <quill-editor
              v-model.trim="form.answer"
              :options="editorOption"
              ref="myQuillEditor"
            />
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注：">
            <el-input
              style="width: 35%"
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
              v-model="form.remarks"
            >
            </el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签：">
            <el-select
              v-model="form.tags"
              multiple
              allow-create
              filterable
              default-first-option
              placeholder="请选择试题标签"
              style="width: 35%"
            >
              <el-option
                v-for="item in tagsList"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 确认提交 -->
          <el-button
            :type="`${this.$route.query.id ? 'success' : 'primary'}`"
            size="default"
            @click="confirm"
            style="margin-left: 100px"
          >
            {{ `确认${$route.query.id ? '修改' : '提交'}` }}
          </el-button>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script>
import { simple as getSubjectListApi } from '@/api/hmmm/subjects.js'
import { simple as getDirectorysListApi } from '@/api/hmmm/directorys.js'
import { list as getEnterpriseListApi } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction, questionType, difficulty } from '@/api/hmmm/constants.js'
import { simple as tagsListApi } from '@/api/hmmm/tags.js'
import { add as addQuestionsNewApi, detail as getQuestionDetailApi, update as updateQusetionsApi } from '@/api/hmmm/questions.js'
export default {
  data () {
    // 题干校验
    var checkQuestion = (rule, value, callback) => {
      if (!value) { return callback(new Error('请输入题干')) }
      callback()
    }
    // 答案解析校验
    var checkAnswer = (rule, value, callback) => {
      if (!value) { return callback(new Error('请输入答案解析')) }
      callback()
    }
    return {
      dialogVisible: false,
      editorOption: { // 富文本编辑器
        theme: 'snow',
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
            ['blockquote', 'code-block'], // 引用  代码块-----['blockquote', 'code-block']
            ['image', 'video', 'link'] // 链接、图片、视频
          ]
        }
      },
      form: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: '', // 省份
        city: '', // 区域
        direction: '', // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: '', // 题干
        options: [ // 选项
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 标签
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        province: [{ required: true, message: '请选择区域', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' },
          { validator: checkQuestion, trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' },
          { validator: checkAnswer, trigger: 'blur' }
        ]
      },
      subjectList: [], // 学科列表
      directorysList: [], // 目录列表
      enterpriseList: [], // 省份列表
      provincesList: [], // 区域列表
      citysList: [], // 区域列表
      directionList: direction || [], // 方向列表
      questionTypeList: questionType, // 题型列表
      difficultyList: difficulty, // 难度列表
      tagsList: [], // 标签列表
      subjectID: '', // 试题详情学科数值
      province: '', // 试题详情省份数值
      questionType: null
    }
  },
  watch: {
    subjectID: {
      immediate: true,
      handler () {
        if (this.$route.query.id) {
          this.changeSubject()
        }
      }
    },
    province: {
      immediate: true,
      handler (newVal) {
        this.citysList = citys(this.form.province)
      }
    },
    '$route.query.id': {
      handler (newVal) {
        if (!newVal) {
          this.form = {
            subjectID: null, // 学科
            catalogID: null, // 目录
            enterpriseID: null, // 企业
            province: '', // 省份
            city: '', // 区域
            direction: '', // 方向
            questionType: 1, // 题型
            difficulty: 1, // 难度
            question: '', // 题干
            options: [ // 选项
              {
                code: 'A',
                title: '',
                img: '',
                isRight: false
              },
              {
                code: 'B',
                title: '',
                img: '',
                isRight: false
              },
              {
                code: 'C',
                title: '',
                img: '',
                isRight: false
              },
              {
                code: 'D',
                title: '',
                img: '',
                isRight: false
              }
            ],
            videoURL: '', // 解析视频
            answer: '', // 答案解析
            remarks: '', // 题目备注
            tags: '' // 标签
          }
          this.directorysList = []
          this.citysList = []
          this.tagsList = []
        }
      }
    }
  },
  mounted () {
    this.getSubjectList()
    this.getEnterpriseList()
    this.getProvincesList()
    this.getQuestionDetail()
  },
  methods: {
    // 确认提交
    async confirm () {
      try {
        await this.$refs.form.validate()
        if (this.$route.query.id) {
          await updateQusetionsApi({
            ...this.form,
            questionType: this.form.questionType + '',
            difficulty: this.form.difficulty + '',
            tags: this.form.tags.toString()
          })
        }
        await addQuestionsNewApi({
          ...this.form,
          questionType: this.form.questionType + '',
          difficulty: this.form.difficulty + '',
          tags: this.form.tags.toString()
        })
        this.$message.success(`试题${this.$route.query.id ? '修改' : '录入'}成功`)
        this.$router.push('/questions/list')
      } catch (error) {
        // console.log(error)
      }
    },
    // 删除图片
    delImg (index) {
      this.form.options[index].img = ''
      // console.log(this.$refs.inp[index])
      this.$refs.inp[index].value = null
    },
    // 增加选项与答案
    addOptions () {
      this.form.options.push({
        code: String.fromCharCode(this.form.options.length + 65),
        title: '',
        img: '',
        isRight: false
      })
    },
    clickFile (index) {
      this.$refs.inp[index].click()
    },
    // 选择图片
    chooseImg (e, index) {
      // console.log(e)
      const files = e.target.files
      if (files.length) { this.form.options[index].img = URL.createObjectURL(files[0]) }
      // const fr = new FileReader()
      // fr.readAsDataURL(e.target.files[0])
      // fr.onload = (e) => {
      //   // console.log(e.target.result)
      //   this.form.options[index].img = e.target.result
      // }
    },
    // 点击单选框
    changeRadio (code) {
      const arr = this.form.options.filter(item => item.code !== code)
      arr.forEach(item => { item.isRight = false })
    },
    // 切换题型
    changeQuestionType () {
      this.form.options.forEach(item => { item.isRight = false }) // 选项
    },
    // 获取区域列表
    changeProvince () {
      this.citysList = []
      this.form.city = ''
      this.citysList = citys(this.form.province)
    },
    // 获取城市列表
    getProvincesList () {
      this.provincesList = provinces()
    },
    // 获取企业列表
    async getEnterpriseList () {
      const { data } = await getEnterpriseListApi()
      // console.log(data)
      this.enterpriseList = data.items
    },
    changeSubjectTo () {
      this.form.catalogID = ''
      this.directorysList = []
      this.form.tags = ''
      this.tagsList = []
      this.changeSubject()
    },
    async changeSubject () {
      // 获取目录列表
      const { data } = await getDirectorysListApi({ subjectID: this.form.subjectID })
      // console.log(data)
      this.directorysList = data
      // 获取标签列表
      const res = await tagsListApi({ subjectID: this.form.subjectID })
      // console.log(res.data)
      this.tagsList = res.data
    },
    // 获取学科目录
    async getSubjectList () {
      const { data } = await getSubjectListApi()
      // console.log(data)
      this.subjectList = data
    },
    // 获取试题详情
    async getQuestionDetail () {
      if (this.$route.query.id) {
        const { data } = await getQuestionDetailApi({ id: this.$route.query.id })
        // console.log(data)
        const arr = []
        data.options.forEach(item => {
          const code = data.options.filter(item => item.code === String.fromCharCode(arr.length + 65))
          arr.push(code[0])
          if (item.isRight === 0) {
            item.isRight = false
          } else if (item.isRight === 1) {
            item.isRight = true
          }
        })
        // console.log(arr)
        // console.log(data)
        this.form = {
          ...data,
          questionType: +data.questionType,
          difficulty: +data.difficulty,
          options: arr,
          tags: data.tags ? data.tags.split(',') : null
        }
        this.subjectID = data.subjectID
        this.province = data.province
        this.questionType = data.questionType
      }
      // 富文本编辑器自动获取焦点处理
      this.$nextTick(function () {
        this.$refs.myQuillEditor.quill.enable(true)
        this.$refs.myQuillEditor.quill.blur()
      })
    }
  }
}
</script>

<style lang="less" scoped>
/* 设置富文本编辑器的默认最小高度  */
/deep/ .ql-editor {
  min-height: 240px;
  display: flex;
}
.upload {
  position: relative;
  cursor: pointer;
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  line-height: 98px;
  text-align: center;
  margin-left: 10px;
  border-radius: 20px;
  .img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 2;
    border-radius: 20px;
  }
  .close {
    position: absolute;
    top: -5px;
    right: -5px;
    z-index: 3;
  }
}
</style>
